package com.foodorder.controller;

import com.foodorder.dto.ApiResponse;
import com.foodorder.entity.Store;
import com.foodorder.entity.User;
import com.foodorder.service.StoreService;
import com.foodorder.service.UserService;
import com.foodorder.service.DataSyncService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;


import java.util.List;

/**
 * 统一数据同步控制器
 * 根据用户角色返回对应权限的数据
 */
@RestController
@RequestMapping("/api/unified")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class UnifiedDataController {
    
    private final StoreService storeService;
    private final UserService userService;
    private final DataSyncService dataSyncService;
    
    /**
     * 统一店铺数据查询接口 - 根据用户角色返回对应数据
     */
    @GetMapping("/stores")
    public ApiResponse<List<Store>> getStores(@RequestParam Long userId) {
        try {
            User user = userService.findById(userId);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            List<Store> stores;
            switch (user.getRole()) {
                case CUSTOMER:
                    // 顾客：只能看到已审核通过且营业中的店铺
                    stores = storeService.getApprovedStores();
                    break;
                    
                case MERCHANT:
                    // 商家：只能看到自己的店铺
                    stores = storeService.getStoresByMerchant(userId);
                    break;
                    
                case ADMIN:
                    // 管理员：可以看到所有店铺
                    stores = storeService.getAllStores();
                    break;
                    
                default:
                    return ApiResponse.error("权限不足");
            }
            
            return ApiResponse.success(stores);
            
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 统一用户信息查询接口
     */
    @GetMapping("/user-info")
    public ApiResponse<User> getUserInfo(@RequestParam Long userId) {
        try {
            User user = userService.findById(userId);
            if (user != null) {
                // 隐藏敏感信息
                user.setPassword(null);
                return ApiResponse.success(user);
            }
            return ApiResponse.error("用户不存在");
            
        } catch (Exception e) {
            return ApiResponse.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查用户权限
     */
    @GetMapping("/check-permission")
    public ApiResponse<Boolean> checkPermission(
            @RequestParam Long userId,
            @RequestParam String resource,
            @RequestParam String action) {
        try {
            User user = userService.findById(userId);
            if (user == null) {
                return ApiResponse.error("用户不存在");
            }
            
            boolean hasPermission = hasPermission(user, resource, action);
            return ApiResponse.success(hasPermission);
            
        } catch (Exception e) {
            return ApiResponse.error("权限检查失败: " + e.getMessage());
        }
    }
    
    /**
     * 权限检查逻辑
     */
    private boolean hasPermission(User user, String resource, String action) {
        User.UserRole role = user.getRole();
        
        switch (resource) {
            case "product":
                if ("view".equals(action)) {
                    return true; // 所有用户都能查看商品
                } else if ("manage".equals(action)) {
                    return role == User.UserRole.MERCHANT || role == User.UserRole.ADMIN;
                }
                break;
                
            case "order":
                if ("view".equals(action)) {
                    return true; // 所有用户都能查看自己相关的订单
                } else if ("manage".equals(action)) {
                    return role == User.UserRole.MERCHANT || role == User.UserRole.ADMIN;
                }
                break;
                
            case "store":
                if ("view".equals(action)) {
                    return true; // 所有用户都能查看店铺
                } else if ("manage".equals(action)) {
                    return role == User.UserRole.MERCHANT || role == User.UserRole.ADMIN;
                }
                break;
                
            case "user":
                if ("view".equals(action)) {
                    return role == User.UserRole.ADMIN; // 只有管理员能查看用户列表
                } else if ("manage".equals(action)) {
                    return role == User.UserRole.ADMIN;
                }
                break;
                
            case "finance":
                return role == User.UserRole.MERCHANT || role == User.UserRole.ADMIN;
        }
        
        return false;
    }
} 